import {
  Controller,
  Get,
  Post,
  Body,
  Param,
  Delete,
  Req,
  Query,
} from '@nestjs/common';
import { FavoriteService } from './favorite.service';
import { CreateFavoriteDto } from './dto/create-favorite.dto';
import { ApiOperation, ApiResponse, ApiTags } from '@nestjs/swagger';
import { Public } from 'src/auth/auth.decorator';
import { Favorite } from './entities/favorite.entity';
import { Response } from '../../infra/schema/response';

@ApiTags('收藏')
@Controller('favorite')
export class FavoriteController {
  constructor(private readonly favoriteService: FavoriteService) {}

  @Public()
  @Post()
  @ApiOperation({ summary: '收藏话题' })
  @ApiResponse({ status: 201, description: '话题收藏成功' })
  create(@Body() createFavoriteDto: CreateFavoriteDto) {
    return this.favoriteService.create(createFavoriteDto);
  }

  @Public()
  @Get()
  @ApiOperation({ summary: '获取所有收藏记录' })
  @ApiResponse({ status: 200, description: '成功获取所有收藏记录' })
  findAll() {
    return this.favoriteService.findAll();
  }

  @Public()
  @Get(':id')
  @ApiOperation({ summary: '根据 ID 获取收藏记录' })
  @ApiResponse({ status: 200, description: '成功获取收藏记录' })
  @ApiResponse({ status: 404, description: '收藏记录不存在' })
  findOne(@Param('id') id: string) {
    return this.favoriteService.findOne(+id);
  }

  @Public()
  @Delete(':id')
  @ApiOperation({ summary: '根据 ID 删除收藏记录' })
  @ApiResponse({ status: 200, description: '收藏记录删除成功' })
  @ApiResponse({ status: 404, description: '收藏记录不存在' })
  remove(@Param('id') id: string) {
    return this.favoriteService.remove(+id);
  }

  @Public()
  @Delete('user/:userId/topic/:topicId')
  @ApiOperation({ summary: '根据用户 ID 和话题 ID 取消收藏' })
  @ApiResponse({ status: 200, description: '取消收藏成功' })
  @ApiResponse({ status: 404, description: '收藏记录不存在' })
  removeByUserAndTopic(
    @Param('userId') userId: string,
    @Param('topicId') topicId: string,
  ) {
    return this.favoriteService.removeByUserAndTopic(+userId, +topicId);
  }

  @Get('is-favorite/:topicId')
  @ApiOperation({ summary: '检查用户是否收藏该话题' })
  @ApiResponse({ status: 200, description: '成功获取收藏状态' })
  async isFavorite(@Param('topicId') topicId: string, @Req() req) {
    const userId = req.user.id; // 假设用户信息在请求对象中
    return this.favoriteService.isFavorite(userId, +topicId);
  }

  @Public()
  @Get('user/:userId')
  @ApiOperation({ summary: '通过用户 ID 获取所有收藏记录（分页）' })
  @ApiResponse({
    status: 200,
    description: '成功获取收藏记录',
    type: [Favorite],
  })
  async findByUserIdWithPagination(
    @Param('userId') userId: number,
    @Query('page') page: number = 1,
    @Query('size') size: number = 10,
  ) {
    const result = await this.favoriteService.findByUserIdWithPagination(
      userId,
      page,
      size,
    );
    return Response.successList(result.data, result.total); // 使用响应工具类返回数据
  }
}
